﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetUniLodz.Models;
using System.Web.Security;
using DotNetUniLodz.HelperClasses;

namespace DotNetUniLodz.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        const int RoleIdUser = 2;
        const int RoleIdAdmin = 1;

        private DotNetULEntities db = new DotNetULEntities();

        //
        // GET: /Account/

        public ActionResult Index()
        {
            var users = db.Users.Include(u => u.Role);
            return View(users.ToList());
        }

        //
        // GET: /Account/Details/5

        public ActionResult Details(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            if (User.Identity.IsAuthenticated)
            {
                ViewBag.IsCurrentUser = user.User_login == User.Identity.Name;
            }
            return View(user);
        }

        //
        // GET: /Account/Create

        [AllowAnonymous]
        public ActionResult Create()
        {
            ViewBag.Role_id = new SelectList(db.Roles, "Role_id", "Role_name");
            return View();
        }

        //
        // POST: /Account/Create

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Create(UserModel user)
        {
            if (ModelState.IsValid)
            {
                User newUser = user.User;
                var isUserInDb = db.Users.Any(u => u.User_login == newUser.User_login);
                if (!isUserInDb)
                {
                    newUser.User_pass = HashLib.Hash.GetHash(user.User_pass, HashLib.HashType.SHA512);
                    newUser.User_regDate = DateTime.Now;
                    newUser.Role_id = RoleIdUser;

                    db.Users.Add(newUser);
                    db.SaveChanges();

                    FormsAuthentication.SetAuthCookie(newUser.User_login, false);

                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("User_login", new Exception("Istnieje!"));
            }

            ViewBag.Role_id = new SelectList(db.Roles, "Role_id", "Role_name", user.Role_id);
            return View(user);
        }

        //
        // GET: /Account/Edit/5

        public ActionResult Edit(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            ViewBag.Role_id = new SelectList(db.Roles, "Role_id", "Role_name", user.Role_id);
            return View(user);
        }

        //
        // POST: /Account/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User user)
        {
            //if (ModelState.IsValid)
            //{
            //    db.Entry(user).State = EntityState.Modified;
            //    db.SaveChanges();
            //    return RedirectToAction("Index");
            //}
            //ViewBag.Role_id = new SelectList(db.Roles, "Role_id", "Role_name", user.Role_id);
            return View(user);
        }

        //
        // GET: /Account/Delete/5

        public ActionResult Delete(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /Account/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            //User user = db.Users.Find(id);
            //db.Users.Remove(user);
            //db.SaveChanges();
            return RedirectToAction("Index");
        }

        [AllowAnonymous]
        public ActionResult Login(string ReturnUrl = "")
        {
            ViewBag.ReturnUrl = ReturnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public object Login(User user, bool rememberMe, string ReturnUrl = "")
        {
            if (Membership.ValidateUser(user.User_login, user.User_pass))
            {
                FormsAuthentication.SetAuthCookie(user.User_login, rememberMe);

                // obsługa returnUrl
                if (!string.IsNullOrWhiteSpace(ReturnUrl) && Url.IsLocalUrl(ReturnUrl))
                {
                    return Redirect(ReturnUrl);
                }
                return RedirectToAction("Index", "Home");
            }
            ViewBag.ReturnUrl = ReturnUrl;
            return View(new UserModel() { User_login = user.User_login, User_pass = user.User_pass });
        }

        public ActionResult Logout()
        {
            if (User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
            }
            return RedirectToAction("Index", "Home");
        }

        [AllowAnonymous]
        public ActionResult ForgottenPassword()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult ForgottenPassword(string userName, string email)
        {
            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(email))
            {
                var user = db.Users.FirstOrDefault(u => u.User_login == userName && u.User_mail == email);
                if (user != null)
                {
                    //TODO wysyłanie nowego hasła na maila :)
                }
            }
            ViewBag.Error = "Coś poszło źle, dane są ok?";
            return View();
        }

        [ChildActionOnly]
        [AllowAnonymous]
        public PartialViewResult _NewsFromUser(string userLogin)
        {
            var articles = Enumerable.Empty<Article>();

            if (!string.IsNullOrWhiteSpace(userLogin))
            {
                var user = db.Users.FirstOrDefault(u => u.User_login == userLogin);
                if (user != null)
                {
                    articles = db.Articles.Where(a => a.User_author == user.User_id).OrderByDescending(a => a.Article_id);
                }
            }

            return PartialView(articles);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}